#_*_coding:utf-8_*_
from django.shortcuts import render
import models
#导入获取不到项目则会报错的异常的模块
from django.shortcuts import render,HttpResponsePermanentRedirect
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth import authenticate,login,logout
#导入forms文件的ArticleForm类方法 ,导入实现图片文件上传用handle_uploaded_file方法
from forms import ArticleForm,handle_uploaded_file

# Create your views here.
def index(request):

    articles = models.Article.objects.all()
    return render(request, 'index.html',{'articles':articles})

def category(request,category_id):
    articles = models.Article.objects.filter(categroy_id=category_id)
    return render(request, 'index.html',{'articles':articles})

def article_detail(request,article_id):
    try:
        article_obj = models.Article.objects.get(id=article_id)
    except ObjectDoesNotExist as e:
        return render(request,'404.html',{'err_msg':u"文章不存在"})
    return render(request,'article.html',{'article_obj':article_obj})

def acc_logout(request):
    #注销，清空seccession
    logout(request)
    return HttpResponsePermanentRedirect('/')
def acc_login(request):
    print (request.POST)
    err_msg = ''
    if request.method == "POST":
        print ('user authention...')
        #使用get来获取用户输入的用户名与密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        #使用Django自带的验证
        user = authenticate(username=username,password=password)
        if user is not None:
            #生成Session
            login(request,user)
            return HttpResponsePermanentRedirect('/')
        else:
            err_msg = "Wrong username or password!"
    return render(request,'login.html',{'err_msg':err_msg})

def new_article(request):
    if request.method == 'POST':
        print(request.POST)
        #有文件也要使用request.FILES获取到
        form = ArticleForm(request.POST,request.FILES)
        if form.is_valid():
            print("--form data:",form.cleaned_data)
            form_data = form.cleaned_data
            form_data['author_id'] = request.user.userprofile.id

            new_img_path = handle_uploaded_file(request,request.FILES['head_img'])
            form_data['head_img'] = new_img_path
            new_article_obj = models.Article(**form_data)
            new_article_obj.save()
            return render(request,'new_article.html',{'new_article_obj':new_article_obj})
        else:
            print('err',form.errors)

    category_list = models.Category.objects.all()
    return render(request,'new_article.html',{'category_list':category_list})